package ru.hh.team02.chat.server.SendMessage.sendingBlockingQueue;

import java.util.LinkedList;
import java.util.List;

public class SimpleBlockingQueue<T> implements BlockingQueue<T> {

	private final List<T> queue = new LinkedList<T>();

	/* (non-Javadoc)
	 * @see ru.hh.team02.chat.server.SendMessage.sendingBlockingQueue.BlockingQueue#get()
	 */
	@Override
	public T get() throws InterruptedException {
		synchronized (this) {
			while (queue.isEmpty()) {
				queue.wait();
			}
			return queue.remove(0);
		}
	}

	/* (non-Javadoc)
	 * @see ru.hh.team02.chat.server.SendMessage.sendingBlockingQueue.BlockingQueue#add(T)
	 */
	@Override
	public void add(T obj) {
		synchronized (this) {
			queue.add(obj);
		}
		this.notify(); // notify one thread blocked in the wait section of get
						// method.
	}

	/* (non-Javadoc)
	 * @see ru.hh.team02.chat.server.SendMessage.sendingBlockingQueue.BlockingQueue#addAll(java.util.List)
	 */
	@Override
	public void addAll(List<T> objects) {
		synchronized (this) {
			queue.addAll(objects);
		}

		// wake up all the waiting threads as there are more then 1 object to
		// process
		this.notifyAll();
	}

}
